<?php


namespace App\Http\Controllers\Sale;


use App\Models\Order;
use App\Models\OrderGoods;
use App\Models\OrderLease;
use App\Models\OrderRate;
use App\Models\ShopTrans;
use App\Models\SaleUser;
use App\Models\SaleUserLogin;
use App\Models\SaleLog;
use App\Models\SaleBillLog;
use App\Services\CommonService;
use App\Services\OrderService;
use App\Services\ExportService;
use App\Services\GoodsService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AmountController extends BaseController
// class AmountController
{
    /**
     * 我的账户
     * @param Request $request
     * @return json
     */
    public function myAmount(Request $request){
        $input = $request->input();
        //test
        $sale_user_id = $this->users['sale_user_id'];
        // $sale_user_id = 1;
        
        $data = SaleUser::where('sale_user_id',$sale_user_id)
                    ->select('balance','balance_end','balance_drawal')
                    ->first();
        $data = $data ? $data->toArray() : array();
        
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$data);
    }
    /**
     * 流水记录
     * @param Request $request
     * @return json
     */
    public function amountLog(Request $request){
        $input = $request->input();
        //test
        $sale_user_id = $this->users['sale_user_id'];
        // $sale_user_id = 1;
        $page = $input['page'] ? $input['page'] : 1;
        $pageSize = $input['pageSize'] ? $input['pageSize'] : CommonService::PAGESIZE;
        $data = SaleBillLog::getBillList($pageSize,$sale_user_id);
        
        // dd($data);
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$data);
    }
    /**
     * 结算中心
     * @param Request $request
     * @return json
     */
    public function settleList(Request $request){
        $input = $request->input();
        //test
        $sale_user_id = $this->users['sale_user_id'];
        // $sale_user_id = 1;
        
        $settle_status = $request->input('settle_status',OrderLease::ORDER_LEASE_SETTLE_STATUS_NO);
        $order_no = $request->input('order_no','');
        $user_name = $request->input('user_name','');
        $shop_name = $request->input('shop_name','');
        $lease_term = $request->input('lease_term','');
        $pay_time = $request->input('pay_time','');
        $start_time = $request->input('start_time','');
        $end_times = $request->input('end_time','');
        $page = $request->input('page',1);
        $pageSize = $request->input('pageSize',10);
        $where = [];
        if(!empty($order_no)){
            $where[] = ['o.trade_no','like','%'.$order_no.'%'];
        }
        if(!empty($user_name)){
            $where[] = ['o.realname','like','%'.$user_name.'%'];
        }
        if(!empty($lease_term)){
            $where[] = ['ol.which_period',$lease_term];
        }
        if(!empty($pay_time)){
            $pay_time = explode('~', $pay_time);
            $where[] = ['ol.pay_time','>=',strtotime($pay_time[0])];
            $where[] = ['ol.pay_time','<',strtotime($pay_time[1])];
        }
        if(!empty($start_time)){
            $time_data = searchTime($start_time);
            $begin_time = $time_data['begin_time'];
            $end_time = $time_data['end_time'];
            $where[] = ['o.begin_time','>=',$begin_time];
            $where[] = ['o.begin_time','<=',$end_time];
        }
        if(!empty($end_times)){
            $time_data2 = searchTime($end_times);
            $begin_time2 = $time_data2['begin_time'];
            $end_time2 = $time_data2['end_time'];
            $where[] = ['ol.reward_time','>=',$begin_time2];
            $where[] = ['ol.reward_time','<=',$end_time2];
        }
        $where[] = ['o.pay_type','!=',Order::ORDER_PAY_TYPE_HUABEI];
        // $where[] = ['ol.status',OrderLease::ORDER_LEASE_STATUS_PAID];
        $where[] = ['o.sale_user_id',$sale_user_id];
        $where1[] = ['ol.reward_type',$settle_status];
        $whereSearch = array_merge($where,$where1);
        
        $order = OrderLease::from('sp_order_lease_2 as ol')->where($whereSearch)
            ->wherein('o.status',OrderService::getOrderStatus(OrderService::ORDER_SETTLE_STATUS))
            ->leftjoin('sp_order_2 as o','o.id','ol.order_id')
            ->leftjoin('sp_order_goods_2 as og','o.id','og.order_id')
            ->select('ol.id as lease_id','o.trade_no','o.seller_id','o.month_total','ol.which_period','o.begin_time','o.end_time','og.goods_title','og.lease_set'
            ,'ol.begin_time as lease_time','ol.pay_type','ol.pay_time','ol.rent','ol.paid_rent','ol.status as lease_status','ol.reward_amount','ol.reward_time','ol.reward_type','o.realname','o.status as order_status','ol.overdue_days','ol.settle_type','ol.reason','o.sync_status','o.financing_type')
            ->orderBy('ol.id','desc')
            ->groupBy('ol.id')
            ->paginate($pageSize);
        $order = obToArray($order);
        // dd($order);
        if(!empty($order['data'])){
            foreach ($order['data'] as $k=>$v){
                $order['data'][$k]['order_type'] = OrderService::getOrderStatusName($v['order_status']);
                $order['data'][$k]['order_time'] = date('Y-m-d',strtotime($v['begin_time'])).'至'.date('Y-m-d',strtotime($v['end_time']));
                $order['data'][$k]['pay_type'] = OrderLease::ORDER_LEASE_PAY_TYPE_LIST[$v['pay_type']];
                $order['data'][$k]['lease_time'] = date('Y-m-d',$v['lease_time']);
                $order['data'][$k]['pay_time'] = date('Y-m-d H:i:s',$v['pay_time']);
                $order['data'][$k]['lease_status'] = OrderLease::ORDER_LEASE_STATUS_LIST[$v['lease_status']];
                $order['data'][$k]['reward_type'] = OrderLease::ORDER_LEASE_SETTLE_STATUS_LIST[$v['reward_type']];
                $order['data'][$k]['financing_type'] = Order::ORDER_FINANCING_TYPE_NAME_LIST[$v['financing_type']];
            }
        }
        $order_count = OrderLease::from('sp_order_lease_2 as ol')->where($where)->wherein('o.status',OrderService::getOrderStatus(OrderService::ORDER_SETTLE_STATUS))
        ->leftjoin('sp_order_2 as o','o.id','ol.order_id')
        ->select('ol.reward_type',DB::raw('count(*) as count'))
        ->groupBy(['ol.reward_type'])
        ->get();
        $order_count = obToArray($order_count);
        // dd($order_count);
        $count['no_settle'] = 0;
        $count['settled'] = 0;
        $count['refuse_settle'] = 0;
        if(!empty($order_count)){
            foreach ($order_count as $item){
                if($item['reward_type'] == OrderLease::ORDER_LEASE_SETTLE_STATUS_NO){
                    $count['no_settle'] = $item['count'];
                }
                if($item['reward_type'] == OrderLease::ORDER_LEASE_SETTLE_STATUS_YES){
                    $count['settled'] = $item['count'];
                }
                if($item['reward_type'] == OrderLease::ORDER_LEASE_SETTLE_STATUS_REFUSE){
                    $count['refuse_settle'] = $item['count'];
                }
            }
        }
        $order['count'] = $count;
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$order);
    }
    
    /**
     * 账单结算列表导出
     */
    public function orderLeaseSettleExport(Request $request){
        //test
        $sale_user_id = $this->users['sale_user_id'];
        // $sale_user_id = 1;
        
        $settle_status = $request->input('settle_status',OrderLease::ORDER_LEASE_SETTLE_STATUS_NO);
        $order_no = $request->input('order_no','');
        $user_name = $request->input('user_name','');
        $shop_name = $request->input('shop_name','');
        $lease_term = $request->input('lease_term','');
        $pay_time = $request->input('pay_time','');
        $start_time = $request->input('start_time','');
        $end_times = $request->input('end_time','');
        $where = [];
        if(!empty($order_no)){
            $where[] = ['o.trade_no','like','%'.$order_no.'%'];
        }
        if(!empty($user_name)){
            $where[] = ['o.realname','like','%'.$user_name.'%'];
        }
        if(!empty($lease_term)){
            $where[] = ['ol.which_period',$lease_term];
        }
        if(!empty($pay_time)){
            $pay_time = explode('~', $pay_time);
            $where[] = ['ol.pay_time','>=',strtotime($pay_time[0])];
            $where[] = ['ol.pay_time','<',strtotime($pay_time[1])];
        }
        if(!empty($start_time)){
            $time_data = searchTime($start_time);
            $begin_time = $time_data['begin_time'];
            $end_time = $time_data['end_time'];
            $where[] = ['o.begin_time','>=',strtotime($begin_time)];
            $where[] = ['o.begin_time','<=',strtotime($end_time)];
        }
        if(!empty($end_times)){
            $time_data2 = searchTime($end_times);
            $begin_time2 = $time_data2['begin_time'];
            $end_time2 = $time_data2['end_time'];
            $where[] = ['ol.settle_time','>=',$begin_time2];
            $where[] = ['ol.settle_time','<=',$end_time2];
        }
        $where[] = ['o.pay_type','!=',Order::ORDER_PAY_TYPE_HUABEI];
        $where[] = ['ol.status',OrderLease::ORDER_LEASE_STATUS_PAID];
        $where1[] = ['ol.reward_type',$settle_status];
        $where1[] = ['o.sale_user_id',$sale_user_id];
        $whereSearch = array_merge($where,$where1);
        $order = OrderLease::from('sp_order_lease_2 as ol')->where($whereSearch)
            ->wherein('o.status',OrderService::getOrderStatus(OrderService::ORDER_SETTLE_STATUS))
            ->leftjoin('sp_order_2 as o','o.id','ol.order_id')
            ->leftjoin('sp_order_goods_2 as og','o.id','og.order_id')
            ->select('ol.id as lease_id','ol.order_id','o.trade_no','o.month_total','ol.which_period','o.begin_time','o.end_time','og.lease_set','og.lease_time','ol.begin_time as lease_time','ol.pay_type','ol.pay_time','ol.rent','ol.paid_rent','ol.status as lease_status','ol.reward_type','ol.reward_amount','ol.reward_time','o.realname','o.mobile','o.prov','o.city','o.area','o.address','o.financing_type','o.status as order_status','ol.overdue_days','ol.settle_type','ol.reason','o.sync_status')->orderBy('ol.id','desc')->get();
        $order = obToArray($order);
        if(!$order){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'无数据');
        }
        $data = [];
        if(!empty($order)){
            foreach ($order as $k=>$v){
                $v['order_type'] = OrderService::getOrderTypeName($v['order_status']);
                $v['order_time'] = date('Y-m-d',strtotime($v['begin_time'])).'至'.date('Y-m-d',strtotime($v['end_time']));
                $v['pay_type'] = OrderLease::ORDER_LEASE_PAY_TYPE_LIST[$v['pay_type']];
                $v['lease_time'] = date('Y-m-d',$v['lease_time']);
                $v['pay_time'] = date('Y-m-d H:i:s',$v['pay_time']);
                $v['lease_status'] = OrderLease::ORDER_LEASE_STATUS_LIST[$v['lease_status']];
                
                $v['order_status'] = OrderService::ORDER_STATUS_NAME_LIST[$v['order_status']];
                $v['reward_type_name'] = OrderLease::ORDER_LEASE_SETTLE_STATUS_LIST[$v['reward_type']];
                $data[] = [
                    'id'=>' '.$v['lease_id'],  //ID
                    'trade_no'=>' '.$v['trade_no'], //订单号
                    'month_total'=>$v['which_period'].'/'.$v['month_total'], //期数
                    'order_time'=>$v['order_time'], //租期
                    'pay_type'=>$v['pay_type'], //支付方式
                    'order_type'=>$v['order_type'], //订单类型
                    'lease_time'=>$v['lease_time'], //预计扣款日
                    'pay_time'=>$v['pay_time'], //实际扣款日
                    'rent'=>$v['rent'], //账单金额
                    'paid_rent'=>$v['paid_rent'], //实付金额
                    'lease_status'=>$v['lease_status'],//支付状态
                    'overdue_days'=>$v['overdue_days'], //逾期天数
                    'reward_amount'=>$v['reward_amount'], //结算租金
                    'reward_time'=>$v['reward_time'], //结算时间
                    'order_status'=>$v['order_status'], //订单状态
                    'reward_type_name'=>$v['reward_type_name'],//结算状态
                ];
            }
        }
        $params = $request->input();
        ExportService::exportFile($params,$data,ExportService::FILE_ORDER_REWARD_LIST);
    }

    /**
     * 获取结算详情
     */
    public function getSettleData(Request $request){
        $lease_id = $request->input('lease_id','');
        if(!empty($lease_id)){
            $order = OrderLease::from('sp_order_lease_2 as ol')->where('ol.id',$lease_id)
                ->wherein('ol.status',[OrderLease::ORDER_LEASE_STATUS_PAID,OrderLease::ORDER_LEASE_STATUS_BUYOUT])
                ->leftjoin('sp_order_2 as o','o.id','ol.order_id')
                ->select('o.trade_no','o.month_total','ol.which_period','ol.rent','ol.paid_rent','ol.reward_amount','ol.reward_time')->first();
            $order = obToArray($order);
            if(!empty($order)){
                
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$order);
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要查看的账单');
        }
    }

    /**
     * 账单结算--单期结算
     */
    public function orderSettle(Request $request){
        $lease_id = $request->input('lease_id');
        if(!empty($lease_id)){
            $order = OrderLease::from('sp_order_lease_2 as ol')->where('ol.id',$lease_id)
                ->wherein('ol.status',[OrderLease::ORDER_LEASE_STATUS_PAID,OrderLease::ORDER_LEASE_STATUS_BUYOUT])
                ->leftjoin('sp_order_2 as o','o.id','ol.order_id')
                ->select('o.id as order_id','o.trade_no','o.uid','o.month_total','o.reward','ol.which_period','ol.rent','ol.paid_rent','ol.reward_amount','ol.reward_time','ol.alipay_trade_no')->first();
            $order = obToArray($order);
            if(!empty($order)){
                $data['reward_type'] = OrderLease::ORDER_LEASE_SETTLE_STATUS_YES;
                $data['reward_amount'] = $order['reward_amount'];
                $data['reward_time'] = date('Y-m-d H:i:s');
                $ol_res = OrderLease::where('id',$lease_id)->update($data);
                if($ol_res){
                    
                    $where = [];
                    $where[] = ['sale_user_id',$this->users['sale_user_id']];
                    $sale = SaleUser::GetSaleUser($where);
                    
                    $sale_bill_data = array(
                        'sale_user_id' => $this->users['sale_user_id'],
                        'money' =>$order['reward_amount'],
                        'balance_before' => $sale['balance'],
                        'balance_after' => $sale['balance']  + $order['reward_amount'],
                        'type' => SaleBillLog::MONEY_PUT,
                        'remark' => '金额：'.$order['reward_amount'],
                        'order_id'=>$order['order_id'],
                        'content' => '分销商'.$this->users['username'].'租金结算账单'.$lease_id,
                    );
                    SaleBillLog::setBillList($sale_bill_data);
                    SaleUser::where(['sale_user_id'=>$this->users['sale_user_id']])->increment('balance',$order['reward_amount']);
                    
                    if($order['which_period'] == 1 && $order['reward']>0){ //第一期结算固定佣金
                        $sale_bill_data_2 = array(
                            'sale_user_id' => $this->users['sale_user_id'],
                            'money' => $order['reward'],
                            'balance_before' => $sale['balance'],
                            'balance_after' => $sale['balance']  + $order['reward'],
                            'type' => SaleBillLog::MONEY_PUT,
                            'remark' => '金额：'.$order['reward'],
                            'order_id'=>$order['order_id'],
                            'content' => '分销商'.$this->users['username'].'固定佣金结算账单'.$order['order_id'],
                        );
                        SaleBillLog::setBillList($sale_bill_data_2);
                        SaleUser::where(['sale_user_id'=>$this->users['sale_user_id']])->increment('balance',$order['reward']);
                    }
                    
                    
                    
                    $data_log = [];
                    $data_log['sale_user_id'] = $this->users['sale_user_id'];
                    $data_log['user_id'] = $this->users['id'];
                    $data_log['remark'] = '金额：'.$order['reward_amount'];
                    $data_log['content'] = '分销商'.$this->users['username'].'租金结算账单';
                    SaleLog::addLog($data_log);
                    
                    if($order['which_period'] == 1 && $order['reward']>0){ //第一期结算固定佣金
                        $data_log_2 = [];
                        $data_log_2['sale_user_id'] = $this->users['sale_user_id'];
                        $data_log_2['user_id'] = $this->users['id'];
                        $data_log_2['remark'] = '金额：'.$order['reward'];
                        $data_log_2['content'] = '分销商'.$this->users['username'].'固定佣金结算账单'.$order['order_id'];
                        SaleLog::addLog($data_log_2);
                    }
                    
                    return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'结算成功');
                }else{
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '结算失败');
                }
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要结算的账单');
        }
    }




}
